package com.pig4cloud.ila.basic.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.pig4cloud.pig.common.core.constant.CommonConstants;
import com.pig4cloud.pig.common.core.constant.QueryConstants;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 自动填充信息
 *
 * @author KonBAI
 * @version 1.0
 * Create by 2020/10/10 23:20
 */
@Component
public class BasicMetaObjectHandler implements MetaObjectHandler {

    /**
     * 执行插入操作
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Object createBy = getFieldValByName(QueryConstants.CREATE_BY, metaObject);
        Object createDate = getFieldValByName(QueryConstants.CREATE_TIME, metaObject);
        Object delFlag = getFieldValByName(QueryConstants.DEL_FLAG, metaObject);

        if (Objects.isNull(createBy) && metaObject.getObjectWrapper().hasGetter(QueryConstants.CREATE_BY)) {
            setFieldValByName(QueryConstants.CREATE_BY, SecurityUtils.getMember().getId(), metaObject);
        }
        if (Objects.isNull(createDate) && metaObject.getObjectWrapper().hasGetter(QueryConstants.CREATE_TIME)) {
            setFieldValByName(QueryConstants.CREATE_TIME, LocalDateTime.now(), metaObject);
        }
        if (Objects.isNull(delFlag) && metaObject.getObjectWrapper().hasGetter(QueryConstants.DEL_FLAG)) {
            setFieldValByName(QueryConstants.DEL_FLAG, CommonConstants.STATUS_NORMAL, metaObject);
        }
    }

    /**
     * 执行更新操作
     * @param metaObject
     */
    @Override
    public void updateFill(MetaObject metaObject) {
        Object updateBy = getFieldValByName(QueryConstants.UPDATE_BY, metaObject);
        Object updateDate = getFieldValByName(QueryConstants.UPDATE_TIME, metaObject);

        if (Objects.isNull(updateBy) && metaObject.getObjectWrapper().hasGetter(QueryConstants.UPDATE_BY)) {
            setFieldValByName(QueryConstants.UPDATE_BY, SecurityUtils.getMember().getId(), metaObject);
        }
        if (Objects.isNull(updateDate) && metaObject.getObjectWrapper().hasGetter(QueryConstants.UPDATE_TIME)) {
            setFieldValByName(QueryConstants.UPDATE_TIME, LocalDateTime.now(), metaObject);
        }
    }
}
